<script>
  import RightToolBar from "@/components/common/right-toolbar";
  export default {
    layout: 'admin',
    name: 'admin-annex',
    components: {
      RightToolBar
    },
    data() {
      return {
        // 客户端初始化
        clientInit: true,
        // 附件配置列表
        annexList: [],
        // 选中附件配置列表
        annexSelection: [],
        // 附件配置总数
        totalNum: 0,
        // 分类枚举列表
        classifyEnumList: [],
        // 状态枚举列表
        statusEnumList: [],
        // 附件配置检索表单显示状态[true-显示 false-隐藏]
        searchFormVisible: true,
        // 附件配置检索表单对象
        searchForm: {
          // 分类
          classify: undefined,
          // 状态
          status: undefined,
          // 当前展示页码
          page: 1,
          // 当前页显示个数
          limit: 10
        },
        // 数据加载状态[false-不加载 true-加载]
        dataLoad: false,
        // 按钮禁用状态[true-禁用 false-可用]
        buttonLoad: false,
      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme;
      }
    },
    async asyncData({ app, params, error }) {
      // 客户端调用直接返回
      if (process.client) return {};
      let searchForm = {
        page: 1,
        limit: 10
      }
      if (params.searchForm) {
        searchForm = JSON.parse(params.searchForm);
      }
      let res;
      try {
        res = await app.$axios.$post('/annex/page/list', searchForm);
      } catch (e) {
        error(e.msg || '网络异常，请求失败');
        return {};
      }
      const data = res.data;

      try {
        res = await app.$axios.$get('/annex/index/enums');
      } catch (e) {
        error(e.msg || '网络异常，请求失败');
        return {};
      }
      const enumData = res.data;

      return {
        clientInit: false,
        annexList: data.data,
        totalNum: data.totalNum,
        classifyEnumList: enumData.classifyEnumList,
        statusEnumList: enumData.statusEnumList,
        searchForm: searchForm
      }
    },
    created() {
      if (process.client) {
        if (this.clientInit) {
          const params = this.$route.params;
          if (params.searchForm) {
            this.searchForm = JSON.parse(params.searchForm);
          }
          // 客户端加载
          this.getAnnexList();
          // 枚举加载
          this.getAnnexEnums();
        }
      }
    },
    methods: {
      /**
       * 分页获取附件配置方法
       */
      getAnnexList() {
        // 开始加载
        this.dataLoad = true;
        this.$axios.$post('/annex/page/list', this.searchForm)
          .then(({ data }) => {
            this.annexList = data.data;
            this.totalNum = data.totalNum;
          })
          .catch(() => {})
          .finally(() => {
            // 结束加载
            this.dataLoad = false;
          });
      },
      /**
       * 获取附件配置枚举方法
       */
      getAnnexEnums() {
        this.$axios.$get('/annex/index/enums')
          .then(({ data }) => {
            this.classifyEnumList = data.classifyEnumList;
            this.statusEnumList = data.statusEnumList;
          })
          .catch(() => {});
      },
      /**
       * 商店检索事件
       */
      searchHandle() {
        this.searchForm.page = 1;

        this.getAnnexList();
      },
      /**
       * 重置检索表单事件
       */
      resetFormHandle() {
        // 重置表单
        this.$refs.searchForm.resetFields();

        this.searchForm.page = 1;
      },
      /**
       * 跳转到附件配置页面事件
       * @param {string} id 主键
       */
      toAnnexConfigPageHandle(id) {
        this.$router.push({ name: 'admin-annex-config',
          params: { id: id, prePageSearchForm: JSON.stringify(this.searchForm) }
        });
      },
      /**
       * 跳转到查看附件配置页面事件
       * @param {string} id 主键
       */
      toAnnexViewPageHandle(id) {
        this.$router.push({ name: 'admin-annex-view',
          params: { id: id, prePageSearchForm: JSON.stringify(this.searchForm) }
        });
      },
      /**
       * 删除附件配置事件
       */
      deleteAnnexHandle() {
        this.$confirm('确认删除选中的附件吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        .then(() => {

          const annexSelection = this.annexSelection;

          const idList = annexSelection.map(annex => annex.id);

          this.buttonLoad = true;
          return this.$axios.$delete('/annex/delete', { data: idList });
        })
        .then(() => {
          this.notify('success', '操作成功', '删除附件完成');
          // 刷新数据
          this.getAnnexList();
        })
        .catch(() => {})
        .finally(() => {
          this.buttonLoad = false;
        });
      },
      /**
       * 每页显示个数变化事件
       * @param {number} size 最新显示个数值
       */
      sizeChangeHandle(size) {
        let searchForm = this.searchForm;
        searchForm.page = 1;
        searchForm.limit = size;
        this.getAnnexList();
      },
      /**
       * '点击特定页码'、'上一页'、'下一页'操作事件
       * @param {number} index 最新页码
       */
      currentChangeHandle(index) {
        let searchForm = this.searchForm;
        if (searchForm.page === index) {
          return;
        }
        searchForm.page = index;
        this.getAnnexList();
      },
      /**
       * 复制附件事件
       */
      copyAnnexHandle() {
        this.$confirm('确认复制选中的附件吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        })
        .then(() => {
          const annex = this.annexSelection[0];

          this.buttonLoad = true;
          return this.$axios.$put('/annex/copy', null, { params: { id: annex.id }});
        })
        .then(() => {
          this.notify('success', '操作成功', '复制附件完成');
          // 刷新数据
          this.getAnnexList();
        })
        .catch(() => {})
        .finally(() => {
          this.buttonLoad = false;
        });
      },
      /**
       * 启用附件配置事件
       * @param {Object} annex 附件配置对象
       */
      useAnnexHandle(annex) {
        this.$confirm(`确定启用‘${annex.classifyName}’吗，版本号：${annex.version}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        })
        .then(() => {
          this.buttonLoad = true;

          return this.$axios.$put('/annex/use', null, { params: { id: annex.id }});
        })
        .then(() => {
          this.notify('success', '操作成功', '启用附件配置完成');

          this.getAnnexList();
        })
        .catch(() => {})
        .finally(() => {
          this.buttonLoad = false;
        });
      }
    }
  }
</script>

<template>
  <div class="annex-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchFormVisible" inline size="mini" :model="searchForm" ref="searchForm"
               @keyup.enter.native="searchHandle">
        <el-form-item prop="classify" label="附件配置检索">
          <el-select v-model="searchForm.classify" clearable placeholder="请选择分类" >
            <el-option v-for="classifyEnum in classifyEnumList" :key="'classifyEnum' + classifyEnum.value"
                       :label="classifyEnum.name" :value="classifyEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
            <el-option v-for="statusEnum in statusEnumList" :key="'status' + statusEnum.value"
                       :label="statusEnum.name" :value="statusEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchHandle" type="primary" icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetFormHandle" plain icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>
    <div class="a-tool">
      <el-button :disabled="dataLoad" @click="toAnnexConfigPageHandle(undefined)"
                 type="primary" size="mini" plain icon="el-icon-plus">添加</el-button>
      <el-button :disabled="annexSelection.length !== 1 || dataLoad || buttonLoad"
                 type="success" size="mini" plain icon="el-icon-copy-document" @click="copyAnnexHandle">复制</el-button>

      <el-button :disabled="annexSelection.length === 0 || dataLoad || buttonLoad" @click="deleteAnnexHandle"
                 type="danger" size="mini" plain icon="el-icon-delete">删除</el-button>

      <right-tool-bar :search-visible="searchFormVisible" :search-load="dataLoad"
                      @toggle-search="searchFormVisible = !searchFormVisible" @refresh-table="getAnnexList" />
    </div>
    <el-table
      v-loading="dataLoad"
      element-loading-text="附件配置列表加载中..."
      element-loading-spinner="el-icon-loading"
      :data="annexList"
      @selection-change="(val) => this.annexSelection = val"
      ref="annexTable"
      class="annex-table"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="classifyName" header-align="center" align="center" label="分类名称">
        <template v-slot="{ row }">
          <div :style="{ '--theme': themeColor }" @click="toAnnexViewPageHandle(row.id)" class="classify">
            {{ row.classifyName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="version" header-align="center" align="center" label="版本号"></el-table-column>
      <el-table-column prop="statusName" header-align="center" align="center" label="状态"></el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" label="创建时间"></el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="创建人"></el-table-column>
      <el-table-column
        header-align="left"
        width="180"
        label="操作">
        <template v-slot="{ row }">
          <el-button v-if="row.status === 1 || row.status === 2" type="text" :disabled="buttonLoad"
                     icon="el-icon-switch-button" @click="useAnnexHandle(row)">
            启用
          </el-button>
          <el-button v-if="row.status === 1" type="text" icon="el-icon-edit"
                     @click="toAnnexConfigPageHandle(row.id)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :disabled="dataLoad"
      :current-page="searchForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchForm.limit"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>
  </div>
</template>

<style scoped>
  .annex-page .a-tool {
    margin-bottom: 7px;
  }
  .annex-page .annex-table .classify:hover {
    --theme: black;
    color: var(--theme);
    cursor: pointer;
  }
  .annex-page .paging {
    text-align: right;
    margin: 7px;
  }
</style>
